<template>
    <div class="app-container">
        <el-row :gutter="16">
            <el-col :span="12">
                <el-card shadow="always">
                    <el-row style="margin-bottom: 20px;">
                        <el-col :span="24">
                            <div>
                                <p style="font-size: 24px; margin-right: 10px;margin-bottom: 5px;">
                                    &nbsp{{
                                        year }} &nbsp年&nbsp{{ batch
                                    }}&nbsp期移动业务网络质量满意度</p>
                                <p style="font-size: 14px;color: #73767a;">&nbsp({{
                                    DateString
                                    }})
                                </p>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <div class="statistic-card">
                                <el-statistic :value="latestBatch.networkSatisfaction" :precision=2>
                                    <template #title>
                                        <div
                                            style="display: inline-flex; align-items: center;font-size: 16px;font-weight: 400;">
                                            满意度
                                        </div>
                                    </template>
                                </el-statistic>
                                <div class="statistic-footer">
                                    <div class="footer-item">
                                        <span>较上周</span>
                                        <span
                                            :class="{ green: compareData.compare1 < 0, red: compareData.compare1 >= 0 }">
                                            {{ compareData.compare1 }} %

                                            <b></b>
                                            <!-- <el-icon>
                                                <template v-if="compareData.compare1 >= 0">
                                                    <CaretTop />
                                                </template>
                                                <template v-if="compareData.compare1 < 0">
                                                    <CaretBottom />
                                                </template>
                                            </el-icon> -->
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="statistic-card">
                                <el-statistic :value="latestBatch.networkSatisfactionLead" :precision=2>
                                    <template #title>
                                        <div
                                            style="display: inline-flex; align-items: center;font-size: 16px;font-weight: 400;">
                                            领先度
                                        </div>
                                    </template>
                                </el-statistic>
                                <div class="statistic-footer">
                                    <div class="footer-item">
                                        <span>较上周</span>
                                        <span
                                            :class="{ green: compareData.compare2 < 0, red: compareData.compare2 >= 0 }">
                                            {{ compareData.compare2 }} %

                                            <b></b>
                                            <!-- <el-icon>
                                                <template v-if="compareData.compare2 >= 0">
                                                    <CaretTop />
                                                </template>
                                                <template v-if="compareData.compare2 < 0">
                                                    <CaretBottom />
                                                </template>
                                            </el-icon> -->
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="statistic-card">
                                <el-statistic :value="latestBatch.base">
                                    <template #title>
                                        <div
                                            style="display: inline-flex; align-items: center;font-size: 16px;font-weight: 400;">
                                            Base
                                        </div>
                                    </template>
                                </el-statistic>
                            </div>
                        </el-col>
                    </el-row>
                    <el-divider content-position="left">指标数据</el-divider>
                    <el-row>
                        <el-col :span="24">
                            <el-table :data="tableData" style="width: 100%" id="tableBox" stripe
                                @row-click="handleClickChange" :row-class-name="tableRowClassName">
                                <el-table-column prop="type" label="类型" align="center" />
                                <el-table-column prop="satisfaction" label="满意度" sortable align="center" />
                                <el-table-column prop="precede" label="领先度" sortable align="center" />
                            </el-table>
                        </el-col>
                    </el-row>
                    <el-divider content-position="left">指标详情</el-divider>
                    <el-row>
                        <el-button type="primary" plain @click="pushToDetail">满意度指标</el-button>
                        <!-- <el-button type="primary" plain>低满修复</el-button> -->
                        <el-button type="primary" plain @click="importData">数据导入</el-button>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" header="满意度趋势图">
                    <div id='trendChart' style="width: 100%;height:455px"></div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="16" style="margin-top: 10px;">
            <el-col :span="12">
                <el-card shadow="always" header="区县满意度数据">
                    <el-table :data="countyTableData" style="width: 100%" id="tableBox" stripe
                        @row-click="handleClickChange" :row-class-name="tableRowClassName">
                        <el-table-column prop="name" label="区县" align="center" />
                        <!-- <el-table-column prop="precede" label="排名" sortable align="center" /> -->
                        <el-table-column label="表现值" align="center">
                            <el-table-column prop="networkSatisfaction" label="网络质量" sortable align="center" />
                            <el-table-column prop="voiceSatisfaction" label="语音质量" sortable align="center" />
                            <el-table-column prop="flowSatisfaction" label="上网质量" sortable align="center" />
                        </el-table-column>
                        <el-table-column label="领先度" align="center">
                            <el-table-column prop="networkSatisfactionLead" label="网络质量" sortable align="center" />
                            <el-table-column prop="voiceSatisfactionLead" label="语音质量" sortable align="center" />
                            <el-table-column prop="flowSatisfactionLead" label="上网质量" sortable align="center" />
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" header="区县满意度对比">
                    <div id='countyBar' style="width: 100%;height:470px"></div>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="importDialogVisible" title="满意度指标" width="50%" v-loading="importLoading">
            <el-form :model="queryParams" label-width="100px">
                <el-form-item label="日期" prop="date">
                    <el-date-picker v-model="queryParams.date" type="daterange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateChange"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label=" " v-if="queryParams.date">
                    ( {{ importDateString }})
                </el-form-item>
                <el-form-item label="文件">
                    <el-upload class="upload-demo" :action="uploadSatisfactionDataUrl" :on-success="uploadSuccess"
                        :on-progress="uploadProgress"
                        :data="{ year: importYear, batch: importBatch, startTime: queryParams.date[0], endTime: queryParams.date[1] }"
                        :show-file-list="false" :headers="headers">
                        <el-button type="primary" icon="Upload">导入</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from "vue";
import * as echarts from 'echarts';
import { ElDropdownItem, ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { querySatisfactionOverview, queryCountySatisfactionData } from '@/api/complain/complain';

const router = useRouter();

const year = ref("");
const batch = ref("")
const latestBatch = ref({})

const DateString = ref("")
const tableData = ref([])

const countyTableData = ref([])
const importDialogVisible = ref(false)
const queryParams = ref({
    date: ""
})
const importDateString = ref("")
const importYear = ref("")
const importBatch = ref("")
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadSatisfactionDataUrl = ref(import.meta.env.VITE_APP_BASE_API + "/complaint/uploadSatisfactionData");
const importLoading = ref(false)
const compareData = ref({})

function loadCountyBar() {
    //获取整体区县列表
    let countyList = [], satisfactionList = [], satisfactionLeadList = []
    for (var i = 0; i < countyTableData.value.length; i++) {
        countyList.push(countyTableData.value[i].name)
        satisfactionList.push(countyTableData.value[i].overallSatisfaction)
        satisfactionLeadList.push(countyTableData.value[i].overallSatisfactionLead)
    }
    var myChart = echarts.init(document.getElementById("countyBar"))
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        toolbox: {
            feature: {
                saveAsImage: { show: true }
            }
        },
        legend: {
            data: ['表现值', '领先度']
        },
        xAxis: [
            {
                type: 'category',
                data: countyList,
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '表现值',
                position: 'left',
                max: 100,
                min: 60,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            {
                type: 'value',
                name: '领先度',
                position: 'right',
                axisLabel: {
                    formatter: '{value} '
                }
            }
        ],
        series: [
            {
                name: '表现值',
                type: 'bar',
                yAxisIndex: 0,
                data: satisfactionList
            },
            {
                name: '领先度',
                type: 'line',
                yAxisIndex: 1,
                data: satisfactionLeadList
            }
        ]
    };
    option && myChart.setOption(option);
}

function loadTrendChart(data) {
    let endTimeList = [], overallSatisfactionList = [], bizSatisfactionList = [], networkSatisfactionList = [], voiceSatisfactionList = [], flowSatisfactionList = []
    let length = data.length > 6 ? 6 : data.length
    for (var i = 0; i < length; i++) {
        endTimeList.push(dateFormatter(data[length - 1 - i].endTime))
        overallSatisfactionList.push(data[length - 1 - i].overallSatisfaction)
        bizSatisfactionList.push(data[length - 1 - i].bizSatisfaction)
        networkSatisfactionList.push(data[length - 1 - i].networkSatisfaction)
        voiceSatisfactionList.push(data[length - 1 - i].voiceSatisfaction)
        flowSatisfactionList.push(data[length - 1 - i].flowSatisfaction)
    }
    var myChart = echarts.init(document.getElementById("trendChart"))
    var option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['综合满意度', '移动业务满意度', '网络质量', '语音质量', '上网质量']
        },
        toolbox: {
            feature: {
                saveAsImage: { show: true }
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: endTimeList
        },
        yAxis: {
            type: 'value',
            scale: true
        },
        series: [
            {
                name: '综合满意度',
                type: 'line',
                data: overallSatisfactionList
            },
            {
                name: '移动业务满意度',
                type: 'line',
                data: bizSatisfactionList
            },
            {
                name: '网络质量',
                type: 'line',
                data: networkSatisfactionList
            },
            {
                name: '语音质量',
                type: 'line',
                data: voiceSatisfactionList
            },
            {
                name: '上网质量',
                type: 'line',
                data: flowSatisfactionList
            }
        ]
    };
    option && myChart.setOption(option);
}

function pushToDetail() {
    router.push("satisfactionDetail");
}

function importData() {
    importDialogVisible.value = true

}

function handleDateChange() {
    if (queryParams.value.date == "") {
        return
    }
    var temp = queryParams.value.date
    var start = temp[0]
    var end = temp[1]
    //判断start和end是在一个季度内
    if (!isSameQuarter(start, end)) {
        ElMessage.error("请选择同一季度的日期")
        queryParams.value = []
        return
    }

    //转换成DateString
    const dateParts = getDateParts(start);
    var batch = Math.ceil(dateParts.month / 3);
    importBatch.value = batch
    importYear.value = dateParts.year
    var tempStr = dateParts.year + "年第" + batch + "期" + formatDate(start) + "-" + formatDate(end)
    importDateString.value = tempStr
}

function uploadSuccess() {
    importLoading.value = false
    importDialogVisible.value = false
    ElMessage.success("导入成功")
}

function uploadProgress() {
    importLoading.value = true
}



function isSameQuarter(dateStr1, dateStr2) {
    // 将日期字符串转换为Date对象  
    const date1 = new Date(dateStr1);
    const date2 = new Date(dateStr2);

    // 获取两个日期的月份（0-11）  
    const month1 = date1.getMonth();
    const month2 = date2.getMonth();

    // 根据月份计算季度（1-4）  
    const quarter1 = Math.ceil((month1 + 1) / 3);
    const quarter2 = Math.ceil((month2 + 1) / 3);

    // 判断两个日期是否在同一季度  
    return quarter1 === quarter2;
}

function getDateParts(dateStr) {
    // 使用"-"作为分隔符分割字符串  
    const parts = dateStr.split('-');

    // 检查分割后的数组是否包含三个元素（年、月、日）  
    if (parts.length !== 3) {
        throw new Error('Invalid date format');
    }

    // 提取年、月、日  
    const year = parseInt(parts[0], 10); // 将年转换为整数  
    const month = parseInt(parts[1], 10); // 将月转换为整数  
    const day = parseInt(parts[2], 10); // 将日转换为整数  

    // 返回包含年、月、日的对象（或者你可以根据需要返回其他格式）  
    return {
        year,
        month,
        day
    };
}

function formatDate(dateStr) {
    // 使用"-"作为分隔符分割字符串  
    const [year, month, day] = dateStr.split('-');
    return `${year}${month.padStart(2, '0')}${day.padStart(2, '0')}`;
}

function dateFormatter(cellValue) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}

function loadSatisfactionOverview() {
    querySatisfactionOverview().then(res => {
        year.value = res.data.year
        batch.value = res.data.batch
        const date = new Date(res.data.endTime);
        var year1 = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var day = ("0" + date.getDate()).slice(-2);
        // 格式化输出
        DateString.value = year1 + "年" + month + "月" + day + "日";

        if (res.data.satisfactionList && res.data.satisfactionList.length > 0) {
            latestBatch.value = res.data.satisfactionList[0]

            //计算满意度增长
            let t1 = res.data.satisfactionList[0].networkSatisfaction;
            let t2 = res.data.satisfactionList[1].networkSatisfaction;
            let compare1 = (t1 - t2) / t2 * 100;

            let x1 = res.data.satisfactionList[0].networkSatisfactionLead;
            let x2 = res.data.satisfactionList[1].networkSatisfactionLead;
            let compare2 = (x1 - x2) / x2 * 100;
            compareData.value = {
                compare1: compare1.toFixed(2),
                compare2: compare2.toFixed(2)
            }

            let tempData = []

            var temp = {
                type: "移动业务满意度",
                satisfaction: latestBatch.value.bizSatisfaction,
                precede: latestBatch.value.bizSatisfactionLead,
            }

            var temp1 = {
                type: "网络质量",
                satisfaction: latestBatch.value.networkSatisfaction,
                precede: latestBatch.value.networkSatisfactionLead,
            }

            var temp2 = {
                type: "语音质量",
                satisfaction: latestBatch.value.voiceSatisfaction,
                precede: latestBatch.value.voiceSatisfactionLead,
            }

            var temp3 = {
                type: "上网质量",
                satisfaction: latestBatch.value.flowSatisfaction,
                precede: latestBatch.value.flowSatisfactionLead,
            }

            tempData.push(temp)
            tempData.push(temp1)
            tempData.push(temp2)
            tempData.push(temp3)
            tableData.value = tempData
        }



        loadTrendChart(res.data.satisfactionList)
        //加载区县数据
        loadCountySatisfactionData(date)

    })
}

function loadCountySatisfactionData(endTime) {
    const date = new Date(endTime);
    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2);
    var day = ("0" + date.getDate()).slice(-2);
    // 格式化输出
    var endTime = year + "-" + month + "-" + day;

    const params = {
        endTime: endTime
    }
    queryCountySatisfactionData(params).then(res => {
        countyTableData.value = res.data
        loadCountyBar(res.data)
    })


}

onMounted(() => {
    loadCountyBar();
})

loadSatisfactionOverview();

</script>

<style scoped>
:global(h2#card-usage ~ .example .example-showcase) {
    background-color: var(--el-fill-color) !important;
}

.el-statistic {
    --el-statistic-content-font-size: 28px;
}

.statistic-card {
    height: 100%;
    padding: 10px;
    border-radius: 4px;
    background-color: #f5f7fab2;
}

.statistic-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-top: 16px;
}

.statistic-footer .footer-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.statistic-footer .footer-item span:last-child {
    position: relative;
    display: inline-flex;
    align-items: center;
    margin-left: 10px;
    font-size: 20px;
    top: -3px;

    /* &::after {
        content: '';
        position: absolute;
        right: -26px;
        top: 50%;
        transform: translateY(-50%);
        width: 22px;
        height: 25px;
        background: url('../../../assets/icons/svg/arrow.svg') left top no-repeat;

        svg {
            fill: red;
            background-color: #ff0000;
        }
    } */

    b {
        width: 22px;
        height: 25px;
        background-size: 100% 100% !important;
        margin-left: 6px;
    }

    &.red {
        color: var(--el-color-error);

        b {
            background: url('../../../assets/icons/svg/arrow_up.svg') left top no-repeat;
        }
    }

    &.green {
        color: var(--el-color-success);

        b {
            background: url('../../../assets/icons/svg/arrow_down.svg') left top no-repeat;
            transform: rotateX(180deg);
        }
    }
}
</style>
